package com.ui.service.Impl;

import com.ui.dao.JedisDao;
import com.ui.service.UserService;
import com.wanmei.commons.JsonUtils;
import com.wanmei.commons.ResultUtils;
import com.wanmei.mapper.UserMapper;
import com.wanmei.pojo.Result;
import com.wanmei.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JedisDao jedisDao;

    @Value("${REDIS_LOGIN_KEY}")
    private String REDIS_LOGIN_KEY;

    private static final String TOKEN_COOKIE = "TOKEN_COOKIE";

    @Override
    public User selectByUserName(String uname, String pwd, HttpServletResponse response) {
        // TODO Auto-generated method stub
        // 1、数据表中查询--根据输入用户名和密码
        // (tel='xx' and pwd='123') or (emai='xxx' and pwd='123')
        User user = userMapper.selectByUserName(uname,pwd);
        // 2、如果存在user对象，生成token
        if (user != null) {
            String token = UUID.randomUUID().toString();
            // 将用户信息保存在redis中，相当于在服务器端创建的session对象
            String jedisKey = REDIS_LOGIN_KEY + "_" + token;
            String jsonValue = JsonUtils.objectToJson(user);
            jedisDao.set(jedisKey, jsonValue);
            jedisDao.expire(jedisKey, 1800);// 设置过期时间

            // 将token放到cookie中
            Cookie cookie = new Cookie(TOKEN_COOKIE, token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }

        return user;
    }

    // 通过token到redis中获取用户存储信息
    public User getRedisByToken(String token) {
        // 通过传递过来的token，到redis中查询是否存在用户信息
        String keyRedis = REDIS_LOGIN_KEY + "_" + token;
        String value = jedisDao.get(keyRedis);
        User user = null;
        if (value != null) {
            return user;
        }
        // redis过期时间重置
        jedisDao.expire(keyRedis, 1800);
        user = JsonUtils.jsonToPojo(value, User.class);
        return user;
    }

    // 删除redis
    public Result logout(String token) {
        // 到redis删除redis值
        if (token == null || token == "") {
            return ResultUtils.fail("注销失败",null,0);
        }
        String keyRedis = REDIS_LOGIN_KEY + "_" + token;
        jedisDao.del(keyRedis);
        return ResultUtils.success("删除成功",null,1);
    }
}
